#include <fcntl.h> /* For O_* constants */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <unistd.h>
#include <thread>
#include <chrono>

#define SHM_NAME "/shm"

int main(void) {
    ///< 创建共享内存文件标识符
    int shm_fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, 0666);
    if (shm_fd == -1) {
        printf("Failed to open shm_open!\n");
        exit(EXIT_FAILURE);
    }

    ///< 设置共享内存文件为8KB
    ftruncate(shm_fd, 8192);

    ///< 获取共享内存文件相关属性信息
    struct stat filestat;
    fstat(shm_fd, &filestat);
    printf("st_size = %ld\n", filestat.st_size);

    ///< 映射共享内存，并获取共享内存的地址
    char *shm_ptr = (char *) mmap(NULL, filestat.st_size, PROT_READ | PROT_WRITE,
                                  MAP_SHARED, shm_fd, 0);

     u_int32_t count = 0;

    ///< 获取共享内存地址中的内容并打印
    while(true)
    {
        printf("read pid = %d，count=%d, %s\n", getpid(), count, shm_ptr);
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(5000ms);
        ++ count;
    }

    return 0;
}
